package cn.com.hhrcw.oauth;

import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.service.ISysUserService;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Constructor;

/**
 * 汇融三方平台登陆
 * @author admin
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class HhicOathController {
    @Autowired
    private IOathService oathService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysBaseAPI sysBaseApi;

    /**
     * 授权登陆
     *
     * @param code 授权码
     * @return
     */
    @SneakyThrows
    @GetMapping("/authorize")
    @AutoLog(value = "授权登陆", logType = 1, ty = "login")
    public Result<?> authorize(String code) {
        JSONObject accessToken = oathService.accessToken(code, "", (ex, request, response) -> {

            log.error("=============>授权登陆登录错误 ,code={},response.getContent()={} ",code,response.getContent());//
            JSONObject content = JSON.parseObject(response.getContent());
            String errorCode = content.getString("errorCode");
            String errorMessage = "";
            try{
                errorMessage = content.getString("errorMessage");
            }catch(Exception e){
                e.printStackTrace();
            }


//            String message = "";
            if(StringUtils.isBlank(errorMessage)){//兼容历史代码
                String client = "invalid_client";
                String grant = "invalid_grant";
                String denied = "access_denied";
                if (StrUtil.equalsIgnoreCase(errorCode, client)) {
                    errorMessage = "客户端验证失败，client_id被停用!";
                } else if (StrUtil.equalsIgnoreCase(errorCode, grant)) {
                    errorMessage = "授权码错误";
                } else if (StrUtil.equalsIgnoreCase(errorCode, denied)) {
                    errorMessage = "禁止访问";
                }else {
                    errorMessage = "errorCode="+errorCode;
                }
            }

            throw new JeecgBootException(errorMessage);
        });
        log.info("统一登录成功accessToken:"+accessToken);
        JSONObject userInfo = oathService.userInfo(accessToken.getString("access_token"));
        log.info("统一登录成功userInfo:"+userInfo);
        LoginUser user = sysBaseApi.getUserByName(userInfo.getString("workno"));
        Assert.notNull(user, "您没有平台登录权限, 请联系管理员");
        //用户登陆标识设置为汇融平台
        sysUserService.lambdaUpdate().eq(SysUser::getId, user.getId()).set(SysUser::getThirdType, "hnic").update();
            String token = JwtUtil.sign(user.getUsername(), user.getPassword(), Dict.create().set("platform", 2));
        Class<?> clz = Class.forName("org.jeecg.modules.shiro.authc.JwtToken");
        Constructor<?> constructor = clz.getConstructor(String.class, String.class, String.class, String.class, Integer.class);
        Object instance = constructor.newInstance(user.getUsername(), user.getPassword(), user.getPhone(), "", 2);
        AuthenticationToken authenticationToken = (AuthenticationToken) instance;
        // 设置token缓存有效时间
        SecurityUtils.getSubject().login(authenticationToken);
//        SecurityUtils.getSubject().checkRole("admin"); 不限制仅admin角色，正常角色都可统一登录
        return Result.ok(token);
    }
}
